package com.plat.net;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

public class UDPtest {
    public static void main(String[] args) throws Exception {
        UDPtest udPtest = new UDPtest();
        udPtest.run(9991);
    }

    public void run(int port) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpClientHandler());
            Channel ch = b.connect("127.0.0.1",9991).sync().channel();
            ByteBuf byteBuf  = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
            ch.writeAndFlush(byteBuf);
            if (!ch.closeFuture().await(15000)) {
                System.out.println("查询超时！！！");
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
            ByteBuf content = msg.content();
            System.out.println("get data: " + content.toString(CharsetUtil.UTF_8));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        }
    }
}
